package com.longma.server.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

@Slf4j
public class AddressUtil {

    private static final  String BAIDU_MAP_URL_FORMAT = "http://api.map.baidu.com/geocoder?location=%s,%s&output=%s&key=%s";
    private static final  String APP_KEY = "OiZmoIVhxz32NBmhYdczvbLhtcYP7Drz";  //app_key
    private static final  String JSON_FORMAT = "json";

    /**
     * 禁止实例化
     */
    private AddressUtil() {
        throw new AssertionError();
    }

    /**
     *  
     *  * 输入经纬度返回地址  失败返回null
     *  * key lat(纬度),lng(经度)
     *   http://api.map.baidu.com/lbsapi/cloud/geocoding-api.htm
     */
    public static String[] obtainAddress(String lat,String lng) {
        HttpURLConnection httpURLConnection;
        try {
            URL url = new URL(String.format(BAIDU_MAP_URL_FORMAT,lat,lng,JSON_FORMAT,APP_KEY));
            httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("GET");
            httpURLConnection.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
            httpURLConnection.setDoInput(true);
            httpURLConnection.setDoOutput(true);
        } catch (Exception e) {
            log.error("baidu map exception " + e.getMessage(),e);
            return null;
        }
        String geocoder = null;
        try(InputStream inputStream = new BufferedInputStream(httpURLConnection.getInputStream());
            ByteArrayOutputStream outputStream =new ByteArrayOutputStream()){
            byte[] streamBuffer = new byte[1024];
            outputStream.write(streamBuffer, 0, inputStream.read(streamBuffer));
            geocoder = outputStream.toString();
        } catch (Exception e) {
            log.error("baidu map exception " + e.getMessage(),e);
        }finally {
            httpURLConnection.disconnect();
        }
        if(null != geocoder){
            try {
                JSONObject jsonObject = JSON.parseObject(geocoder);
                // 获取成功
                if ("OK".equals(jsonObject.get("status"))) {
                    JSONObject result = (JSONObject) jsonObject.get("result");
                    JSONObject addressComponent = (JSONObject) result.get("addressComponent");
                    String []address = new String[3];
                    address[0] = (String) addressComponent.get("province");
                    address[1] = (String) addressComponent.get("city");
                    address[2] = (String) addressComponent.get("district");
                    return address;
                }
            }catch(Exception e){
                log.error("baidu map exception " + e.getMessage(),e);
            }
        }
        return null;
    }
}
